<template>
  <!-- 请款单详情-->
  <a-modal :width="1200" v-model:visible="showBillDetail" top="8vh" :title="`请款详情-货款${detailInfo.settleType === 1 ? '现结' : '月结'}`" :footer="false" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <div class="pay-detail-w">
      <div class="base-info">
        <a-row :gutter="10">
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">请款单号：</span>
              <span class="val">{{ detailInfo.billNo }}</span>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">类型：</span>
              <span class="val">{{ `货款${detailInfo.settleType === 1 ? '现结' : '月结'}` }}</span>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">请款状态：</span>
              <span class="val">{{ paymentStatusMap[detailInfo.paymentStatus] }}</span>
            </div>
          </a-col>
        </a-row>
        <a-row :gutter="20">
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">应付对象：</span>
              <span class="val">{{ detailInfo.supplierName }}</span>
              <span style="color: #999">({{ detailInfo.supplierCode }})</span>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">申请人：</span>
              <span class="val">{{ detailInfo.requestUname }}</span>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">申请日期：</span>
              <span class="val">{{ $setTime(detailInfo.gmtCreate, 'YYYY-MM-DD') }}</span>
            </div>
          </a-col>
        </a-row>
        <a-row :gutter="20">
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">紧急程度：</span>
              <span class="val">{{ urgentStatusMap[detailInfo.urgentStatus] }}</span>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">审核人：</span>
              <span class="val">{{ detailInfo.auditUname }}</span>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">审核时间：</span>
              <span class="val">{{ $setTime(detailInfo.gmtAudit, 'YYYY-MM-DD HH:mm') }}</span>
            </div>
          </a-col>
        </a-row>
        <a-row :gutter="20">
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">期望付款日期：</span>
              <span class="val">{{ $setTime(detailInfo.gmtExpectedPayment, 'YYYY-MM-DD') }}</span>
              <div style="margin-left: 5px" v-if="detailInfo.paymentStatus == 10 || detailInfo.paymentStatus == 20 || detailInfo.paymentStatus == 30" v-html="getSurplusTime(detailInfo.gmtExpectedPayment)"></div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">附件：</span>
              <p v-if="detailInfo.attachment" class="val">
                <span>{{ detailInfo.attachment }}</span>
                <icon-to-bottom style="margin-left: 10px" class="cursor" @click="downloadFile(detailInfo.attachment)" />
              </p>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <span class="label">备注：</span>
              <span class="val">{{ detailInfo.remark || '--' }}</span>
            </div>
          </a-col>
        </a-row>
      </div>
      <div class="account-w">
        <div class="header">收款账户</div>
        <div class="flex-c account-info">
          <p style="margin-right: 30px">
            <span>收款类型：</span>
            <span>{{ detailInfo.type === 1 ? '公司' : '个人' }}</span>
          </p>
          <p style="margin-right: 30px">
            <span>开户银行：</span>
            <span>{{ detailInfo.bank }}</span>
          </p>
          <p>
            <span>银行卡号：</span>
            <span>{{ detailInfo.account }}</span>
          </p>
        </div>
      </div>
      <a-tabs>
        <a-tab-pane key="1" title="付款">
          <div class="pay-info-w" v-if="detailType == 'pay'">
            <a-form ref="formRef" :model="detailInfo" :rules="rules">
              <a-row :gutter="20">
                <a-col :span="12">
                  <a-form-item label="付款金额：" label-col-flex="100px">
                    <p>￥{{ detailInfo.requestAmount }}</p>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="已付款金额：" label-col-flex="120px">
                    <p>￥{{ detailInfo.paidAmount }}</p>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="20">
                <a-col :span="12">
                  <a-form-item label="本次付款：" label-col-flex="100px">
                    <span>￥</span>
                    <a-input-number style="width: 100px" v-model="detailInfo.requestAmount" placeholder="" disabled />
                    <template v-if="exchangeRate">
                      <span style="margin: 0 20px 0 10px; font-size: 12px">${{ ((detailInfo.requestAmount || 0) / (exchangeRate || 0)).toFixed(2) }}</span>
                      <a-popover content="此处汇率取实际付款时间对应的系统本地汇率">
                        <p style="font-size: 12px">
                          <span>汇率{{ exchangeRate }}</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                  </a-form-item>
                </a-col>
                <a-col :span="10">
                  <a-form-item field="gmtPayment" label="实际付款时间：" label-col-flex="120px">
                    <a-date-picker v-model="detailInfo.gmtPayment" @change="getRateList" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="20">
                <a-col :span="12">
                  <a-form-item label="附件：" label-col-flex="100px">
                    <div>
                      <div style="width: 300px; margin-bottom: 5px">
                        <a-tag color="arcoblue" style="width: 100%" v-if="detailInfo.paymentAttachment" closable @close="detailInfo.paymentAttachment = ''">
                          <p class="text-limit">{{ detailInfo.paymentAttachment }}</p>
                        </a-tag>
                      </div>
                      <a-upload action="/" :custom-request="uplaodFile" accept=".png,.jpg,.webp" :show-file-list="false">
                        <template #upload-button>
                          <a-button size="mini" type="outline">
                            <template #icon>
                              <icon-upload />
                            </template>
                            <template #default>上传附件</template>
                          </a-button>
                        </template>
                      </a-upload>
                      <p style="font-size: 12px; color: #999">上传支付水单截图</p>
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="user.id" label="付款人：" label-col-flex="120px">
                    <a-select v-model="detailInfo.user" value-key="id" placeholder="请选择" style="width: 100%">
                      <a-option v-for="(user, index) in userList" :key="index" :value="user" :label="user.userName" />
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-item field="paymentRemark" label="备注：" label-col-flex="100px">
                    <a-textarea v-model="detailInfo.paymentRemark" placeholder=" " allow-clear />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
            <div class="handle-btn">
              <a-popconfirm content="请再次确认是否已完成付款？" @ok="submitPay">
                <a-button type="primary" :loading="submitLoading">确认付款</a-button>
              </a-popconfirm>
            </div>
          </div>
          <div class="pay-info-w" v-else>
            <a-form ref="formRef" :model="detailInfo">
              <a-row :gutter="20">
                <a-col :span="12">
                  <a-form-item label="付款金额：" label-col-flex="100px">
                    <p>￥{{ detailInfo.requestAmount }}</p>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="已付款金额：" label-col-flex="120px">
                    <span>￥{{ detailInfo.paidAmount }}</span>
                    <template v-if="exchangeRate">
                      <span style="margin: 0 20px; font-size: 12px">${{ ((detailInfo.paidAmount || 0) / (exchangeRate || 0)).toFixed(2) }}</span>
                      <a-popover content="此处汇率取实际付款时间对应的系统本地汇率">
                        <p style="font-size: 12px">
                          <span>汇率{{ exchangeRate }}</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="20">
                <a-col :span="12">
                  <a-form-item label="实际付款时间：" label-col-flex="100px">
                    <p>{{ $setTime(detailInfo.gmtPayment, 'YYYY-MM-DD') }}</p>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="付款人：" label-col-flex="120px">
                    <p>{{ detailInfo.paymentUname }}</p>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="20">
                <a-col :span="24">
                  <a-form-item label="附件：" label-col-flex="100px">
                    <a-image v-if="detailInfo.paymentAttachment" width="80" height="80" fit="contain" :src="detailInfo.paymentAttachment" />
                    <p v-else>--</p>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-item label="备注：" label-col-flex="100px">
                    <p>{{ detailInfo.paymentRemark || '--' }}</p>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" title="关联单据">
          <div class="item-w">
            <div class="total-w flex-c">
              <p style="margin-right: 20px">
                <span class="label">本次请款金额：</span>
                <span>￥{{ getTotalVal('currentRequestAmount') }}</span>
              </p>
              <p style="margin-right: 20px">
                <span class="label">已付款金额：</span>
                <span>￥{{ getTotalVal('paidAmount') }}</span>
              </p>
              <p>
                <span class="label">请款中金额：</span>
                <span>￥{{ getTotalVal('requestAmount') }}</span>
              </p>
            </div>
          </div>
          <a-table v-if="detailInfo.paymentPoolVOList" class="table-two-line" :data="detailInfo.paymentPoolVOList" :scroll="{ x: '100%' }" size="mini" :pagination="false">
            <template #columns>
              <a-table-column title="结算类型" :width="70" key="settleType">
                <template #cell="{ record }">
                  <p>{{ record.settleType === 1 ? '现结' : '月结' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="采购单号" :width="110">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight">{{ record.purchaseNo || '--' }}</p>
                    <CopyText :val="record.purchaseNo" class="popup-edit-icon-hover" />
                  </a-space>
                  <p style="color: #999">{{ purchaseStatusMap[record.purchaseStatus] }}</p>
                </template>
              </a-table-column>
              <a-table-column title="交货单号" :width="110">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight">{{ record.deliveryNo || '--' }}</p>
                    <CopyText :val="record.deliveryNo" class="popup-edit-icon-hover" />
                  </a-space>
                  <p style="color: #999">{{ deliveryStatusMap[record.deliveryStatus] }}</p>
                </template>
              </a-table-column>
              <a-table-column title="付款状态" :width="80" key="paymentStatus">
                <template #cell="{ record }">
                  <p>{{ payStatusMap[record.paymentStatus] || record.paymentStatus }}</p>
                </template>
              </a-table-column>
              <a-table-column title="请款状态" :width="80" key="requestStatus">
                <template #cell="{ record }">
                  <p>{{ requestStatusMap[record.requestStatus] }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="paidAmount" :width="100" key="paidAmount">
                <template #title>
                  <a-popover content="已完成支付的请款单金额">
                    <p>
                      <span>已付金额</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record }">
                  <p>￥{{ record.paidAmount }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="unpaidAmount" :width="100" key="unpaidAmount">
                <template #title>
                  <a-popover content="未支付金额=到货金额-已支付金额">
                    <p>
                      <span>未付金额</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record }">
                  <p>￥{{ record.unpaidAmount }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="requestAmount" :width="100" key="requestAmount">
                <template #title>
                  <a-popover content="请款中金额=请款单状态为待支付">
                    <p>
                      <span>请款中金额</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record }">
                  <p>￥{{ record.requestAmount }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="requestAmount" title="本次请款金额" :width="100" key="currentRequestAmount">
                <template #cell="{ record }">
                  <p>￥{{ record.currentRequestAmount }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="gmtBillCreate" title="采购单创建时间" :width="130">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtBillCreate, 'YYYY-MM-DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="gmtBillSign" title="交货签收时间" :width="130">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtBillSign, 'YYYY-MM-DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="purchaseUname" title="采购员" :width="70" />
              <a-table-column title="备注" key="remark" :width="120">
                <template #cell="{ record }">
                  <TextLimit :val="record.remark || '--'" />
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { payPaymentOrder, getPaymentOrderInfo } from '@/api/purchase'
  import useBaseDataStore from '@/store/modules/base-data'
  import useUserStore from '@/store/modules/user'
  import { upload } from '@/api/base'
  import { findExchangeRateList } from '@/api/system'
  import dayjs from 'dayjs'

  onMounted(() => {
    getUserList()
    setDefaultList()
  })

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentId: {
      type: String,
    },
    detailType: {
      type: String,
      default: 'detail',
    },
  })
  const detailInfo = ref<any>({})
  const rules = ref({
    gmtPayment: [{ required: true, message: '请选择期望付款日期' }],
    'user.id': [{ required: true, message: '请选择申请人' }],
  })
  const formRef = ref()
  const showBillDetail = ref(props.isShow)
  const submitLoading = ref(false)
  const useBaseData = useBaseDataStore()
  const userList = ref<Array<any>>([])
  const userStore = useUserStore()
  const exchangeRate = ref(7)
  const requestStatusMap = {
    10: '未请款',
    20: '部分请款',
    30: '已请款',
    40: '已结束请款',
  }
  const urgentStatusMap = {
    0: '正常',
    1: '加急',
    2: '紧急',
  }
  const purchaseStatusMap = {
    0: '已作废',
    1: '草稿中',
    10: '待审核',
    20: '待接单',
    30: '待交货',
    40: '交货中',
    50: '已交货',
    60: '已完成',
    61: '已截单',
  }
  const deliveryStatusMap = {
    0: '已作废',
    10: '待配货',
    20: '待出库',
    30: '待签收',
    40: '待入库',
    50: '入库中',
    60: '已入库',
  }
  const paymentStatusMap = {
    10: '待审核',
    20: '待付款',
    30: '已驳回',
    40: '已完成',
    0: '已作废',
  }
  const payStatusMap = {
    10: '未付款',
    20: '部分付款',
    30: '已付款',
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    userList.value = useBaseData.userList
  }
  // 初始化数据
  async function setDefaultList() {
    const res: any = await getPaymentOrderInfo({ id: props.currentId })
    detailInfo.value = res?.data || []
    if (props.detailType == 'pay') {
      detailInfo.value.user = {
        id: userStore.userId,
        userName: userStore.userName,
      }
    }
    // 获取汇率
    getRateList()
  }
  // 获取商品列表
  async function getRateList() {
    if (!detailInfo.value.gmtPayment) {
      exchangeRate.value = 0
      return
    }
    const res: any = await findExchangeRateList({
      gmtRate: dayjs(detailInfo.value.gmtPayment).format('YYYY-MM'),
    })
    exchangeRate.value = res?.data?.find((el: any) => el.currency == 'USD')?.localRate || 0
  }
  // 剩余时间
  function getSurplusTime(time: string) {
    if (!time) return '--'
    let _time = dayjs(time).format('YYYY-MM-DD 23:59:59')
    let hours = dayjs(_time).diff(dayjs(), 'hour')
    if (hours > 0) {
      return `<span style="color: rgb(var(--warning-5))">剩余${parseInt(hours / 24)}天${hours % 24}小时</span>`
    } else {
      let _hours = hours * -1
      return `<span class="warningColor">超时${parseInt(_hours / 24)}天${_hours % 24}小时</span>`
    }
  }
  // 获取合计数量
  function getTotalVal(key: string) {
    return detailInfo.value.paymentPoolVOList?.reduce((acc: number, item: any) => {
      acc += Number(item[key] || 0)
      return acc
    }, 0)
  }
  // 上传附件
  async function uplaodFile(options: any) {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      detailInfo.value.paymentAttachment = res.data.publicUrl
    }
  }
  // 确认
  async function submitPay() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return

    const res = await payPaymentOrder({
      attachment: detailInfo.value.paymentAttachment,
      gmtPayment: detailInfo.value.gmtPayment,
      id: detailInfo.value.id,
      paidAmount: detailInfo.value.requestAmount,
      paymentUid: detailInfo.value.user?.id,
      paymentUname: detailInfo.value.user?.userName,
      remark: detailInfo.value.paymentRemark,
    })
    if (!res) return false
    Message.success('确认付款成功')
    emit('success')
    closedDialog()
  }
  // 关闭
  function closedDialog() {
    showBillDetail.value = false
    emit('closed')
  }
  //  下载
  function downloadFile(url: string) {
    let _url = url
    if (_url.indexOf('?') > -1) {
      _url += '&response-content-type=application/octet-stream'
    } else {
      _url += '?response-content-type=application/octet-stream'
    }
    let link = document.createElement('a')
    link.href = _url
    link.click()
  }
</script>
<style lang="less" scoped>
  .pay-detail-w {
    height: calc(84vh - 100px);
    overflow-x: hidden;
    overflow-y: auto;
    .base-info {
      .arco-row {
        margin-bottom: 10px;
        .label {
          width: 100px;
          text-align: right;
          flex-shrink: 0;
        }
        .val {
          color: #666;
          word-break: break-all;
        }
      }
    }
  }
  .account-w {
    margin-bottom: 20px;
    .header {
      padding: 0 10px;
      font-weight: bold;
      margin-bottom: 10px;
      margin-top: 20px;
      border-left: 2px solid rgb(var(--primary-6));
    }
    .account-info {
      color: #666;
      margin-left: 16px;
    }
  }
  .pay-info-w {
    width: 900px;
    border: 1px solid #ddd;
    padding: 10px;
    margin-top: 10px;
    .handle-btn {
      text-align: right;
    }
  }
  .item-w {
    .total-w {
      font-weight: bold;
      padding: 10px;
      .label {
        color: #999;
        font-weight: normal;
      }
    }
  }
</style>
